var nApp = {
  // Application Constructor
  initialize: function() {
    this.bindEvents();
  },
  // Bind Event Listeners
  //
  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
  },
  // deviceready Event Handler
  //
  // The scope of 'this' is the event. In order to call the 'receivedEvent'
  // function, we must explicity call 'nApp.receivedEvent(...);'
  onDeviceReady: function() {
    nApp.receivedEvent('deviceready');
  },
  // Update DOM on a Received Event
  receivedEvent: function(id) {
    console.log('index.js deviceready');
    var pushNotification = window.plugins.pushNotification;
    pushNotification.register(nApp.successHandler, nApp.errorHandler, {
      "senderID": "1089894511537",
      "ecb": "nApp.onNotificationGCM"
    });
  },
  successHandler: function(result) {
    console.log('Callback Success! Result = ' + result)
  },
  errorHandler: function(error) {
    console.log(error);
  },
  onNotificationGCM: function(e) {    
    switch (e.event) {        
      case 'registered':
        if (e.regid.length > 0) {                    
          console.log("Regid " + e.regid);
          console.log("device.uuid: " + device.uuid);
          $deviceToken = e.regid;
          $.ajax({
            type: 'POST',
            url: $host + 'push/android/register.php',
            data: {
              regId: e.regid,
              uuid: device.uuid,
              version: AppVersion
            },
            success: function(r) {
              console.log('register on beful success: ' + e.regid + '  ' + r);
            },
            error: function(e) {
              console.log('error: ' + JSON.stringify(e));
            }
          });
        }
        break;             
      case 'message':
        // this is the actual push notification. its format depends on the data model from the push server
        if (getCurrentViewId() != "#home-page-view") {
          view_promotion_post(e.payload.postId);
        }

        break;             
      case 'error':
        console.log('GCM error = ' + e.msg);            
        break;             
      default:
        console.log('An unknown GCM event has occurred');              
        break;        
    };
  }
};

function view_promotion_post(postId) {
  $.ajax({
    type: 'get',
    url: 'http://mapp.vietjetair.com:8000/api/cms/?json=1&p=' + postId + '&lang=' + localStorage.lang,
    success: function(ret) {
      var post = {
        title: ret.post.title,
        content: ret.post.content,
        thumbnail: ret.post.thumbnail_images.medium,
        url: ret.post.url
      };

      $promotion = {
        posts: [post],
        index: 0
      };
      window.location.href = '#src/promotion/step2_detail.html';
    }
  });
};
